package cn.bugstack.domain.trade.service.lock.filter;

import cn.bugstack.domain.trade.adapter.repository.ITradeRepository;
import cn.bugstack.domain.trade.model.entity.GroupBuyActivityEntity;
import cn.bugstack.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import cn.bugstack.domain.trade.model.entity.TradeRuleLockCommandEntity;
import cn.bugstack.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import cn.bugstack.types.design.framework.link.model2.handler.ILogicHandler;
import cn.bugstack.types.enums.ResponseCode;
import cn.bugstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: 小新
 * @Date: 2025/8/17 19:30
 * @Description: 锁单拼团库存占用过滤
 * @Version: v1.0
 */
@Slf4j
@Service
public class TeamStockOccupyRuleFilter implements ILogicHandler<TradeRuleLockCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {

    @Resource
    private ITradeRepository repository;

    @Override
    public TradeLockRuleFilterBackEntity apply(TradeRuleLockCommandEntity requestParameter, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        // 1. 获取teamId判断是否是第一次拼团，如果是第一次拼团不对其进行库存限制
        String teamId = requestParameter.getTeamId();
        if(StringUtils.isBlank(teamId)){
            return TradeLockRuleFilterBackEntity.builder()
                    .userTackOrderCount(dynamicContext.getUserTakeOrderCount())
                    .build();
        }
        // 2. 获取活动信息
        GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivity();
        Integer target = groupBuyActivity.getTarget();
        Integer validTime = groupBuyActivity.getValidTime();

        // 3. 获取key
        String teamSocketKey = dynamicContext.generateTeamStockKey(teamId);
        String teamSocketRecoveryKey = dynamicContext.generateRecoveryTeamStockKey(teamId);

        boolean status=repository.occupyTeamStock(teamSocketKey, teamSocketRecoveryKey, target, validTime);
        if(!status){
            log.info("活动库存缓存不足，teamSocketKey:{}", teamSocketKey);
            throw new AppException(ResponseCode.E0008);
        }
        return TradeLockRuleFilterBackEntity.builder()
                .userTackOrderCount(dynamicContext.getUserTakeOrderCount())
                .teamSocketKey(teamSocketKey)
                .teamSocketRecoveryKey(teamSocketRecoveryKey)
                .build();
    }
}
